

import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:xreader/app/app_routes.dart';
import 'package:xreader/common/app_config.dart';
import 'package:xreader/logs/log.dart';
import 'package:xreader/model/t_book_entity.dart';
import 'package:xreader/params/book_params.dart';
import 'package:xreader/service/book_service.dart';
import 'package:xreader/vo/page_info.dart';

class BookLibController extends GetxController{

  String searchText = '';//关键词搜索

  ScrollController scrollController = ScrollController();
  List<TBookEntity> datas = [];
  bool isLoading = false;
  bool hasNext = true;
  int curPage = 0;
  void loadMore() async  {
    if (scrollController.position.pixels ==
        scrollController.position.maxScrollExtent &&
        !isLoading && hasNext) {
      await searchData(this.curPage+1,true);
    }

  }
  static BookLibController get to => Get.find();

  //搜索数据
  searchData(int pageIndex,bool append) async {
    BookParams params = BookParams();
    params.page = pageIndex;
    params.word = searchText;
    params.pageSize =AppConfig.LIST_PAGE_SIZE;//默认30条
    curPage = pageIndex;
    isLoading = true;
    update();
    PageInfoVo<TBookEntity> pageInfo = await BookService.queryTBookPage(params);
    Log.i("curPage=${curPage} datas=${pageInfo.data}");
    hasNext = (pageInfo.totalPage ?? 0) > (pageInfo.page ?? 1);
    if(!append){
      datas = [];
    }
    datas.addAll(pageInfo.data ?? []);
    isLoading = false;
    update();
  }

  gotoBookReader(TBookEntity info){
    Get.toNamed(AppRoutes.BOOK_READER,arguments:info);
  }
  gotoBookDetail(TBookEntity info){
    Get.toNamed(AppRoutes.BOOK_DETAIL,arguments:info);
  }


  @override
  void onInit() {
    Log.i("BookLibController------初始化--->");
    scrollController = ScrollController();
    searchData(1,false);
    // 添加滚动监听器
    scrollController.addListener(loadMore);
    super.onInit();
  }
  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }
}